import aiohttp
from typing import Dict, Any, Optional
from ..core.exceptions import NetworkError

class PackageAPI:
    def __init__(self, base_url: str, api_key: Optional[str] = None):
        self.base_url = base_url.rstrip('/')
        self.api_key = api_key

    def _get_headers(self) -> Dict[str, str]:
        """获取请求头"""
        headers = {
            'Accept': 'application/json',
            'User-Agent': 'PackageManager/1.0'
        }
        if self.api_key:
            headers['Authorization'] = f'Bearer {self.api_key}'
        return headers

    async def get_package_info(self, package_name: str, version: str = "latest") -> Dict:
        """获取包信息"""
        url = f"{self.base_url}/packages/{package_name}/{version}"
        
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=self._get_headers()) as response:
                if response.status == 200:
                    return await response.json()
                else:
                    raise NetworkError(
                        f"获取包信息失败: HTTP {response.status}"
                    )

    async def search_packages(self, query: str) -> Dict[str, Any]:
        """搜索包"""
        url = f"{self.base_url}/search"
        params = {'q': query}
        
        async with aiohttp.ClientSession() as session:
            async with session.get(
                url,
                params=params,
                headers=self._get_headers()
            ) as response:
                if response.status == 200:
                    return await response.json()
                else:
                    raise NetworkError(
                        f"搜索失败: HTTP {response.status}"
                    )